<template>
  <div class="stock-list-container">
    <div class="table-container">
      <div class="table-header">
        <div class="header-left">
          <el-button type="primary" class="create-btn" @click="handleRefresh">
            <el-icon class="btn-icon">
              <RefreshRight />
            </el-icon>
            刷新数据
          </el-button>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
            class="date-picker"
          />
        </div>
        <el-input v-model="search" size="large" placeholder="搜索股票代码..." class="search-input" prefix-icon="Search" />
      </div>

      <el-table 
        :data="filterTableData" 
        style="width: 100%" 
        class="water-drop-table" 
        :header-cell-style="{
          background: 'rgba(236, 245, 255, 0.6)',
          color: '#409EFF',
          fontWeight: 'bold'
        }"
        border
        stripe
        :max-height="550"
        v-loading="loading">
        <el-table-column label="日期" prop="date" align="center" width="120" sortable>
          <template #default="scope">
            <div class="table-cell-content">
              <el-icon class="cell-icon">
                <Calendar />
              </el-icon>
              <span>{{ scope.row.date }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="股票代码" prop="code" align="center" width="100" sortable>
          <template #default="scope">
            <div class="table-cell-content">
              <el-icon class="cell-icon">
                <Notebook />
              </el-icon>
              <span>{{ scope.row.code }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="开盘" prop="open" align="center" width="100" sortable>
          <template #default="scope">
            <span>{{ scope.row.open.toFixed(2) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="收盘" prop="close" align="center" width="100" sortable>
          <template #default="scope">
            <span :class="getPriceClass(scope.row.priceChange)">{{ scope.row.close.toFixed(2) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="最高" prop="high" align="center" width="100" sortable>
          <template #default="scope">
            <span class="price-up">{{ scope.row.high.toFixed(2) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="最低" prop="low" align="center" width="100" sortable>
          <template #default="scope">
            <span class="price-down">{{ scope.row.low.toFixed(2) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="成交量(手)" prop="volume" align="center" width="120" sortable>
          <template #default="scope">
            <span>{{ formatNumber(scope.row.volume) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="成交额(元)" prop="amount" align="center" width="140" sortable>
          <template #default="scope">
            <span>{{ formatCurrency(scope.row.amount) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="振幅(%)" prop="amplitude" align="center" width="100" sortable>
          <template #default="scope">
            <span>{{ scope.row.amplitude.toFixed(2) }}%</span>
          </template>
        </el-table-column>

        <el-table-column label="涨跌幅(%)" prop="priceChange" align="center" width="120" sortable>
          <template #default="scope">
            <span :class="getPriceClass(scope.row.priceChange)">
              {{ scope.row.priceChange > 0 ? '+' : '' }}{{ scope.row.priceChange.toFixed(2) }}%
            </span>
          </template>
        </el-table-column>

        <el-table-column label="涨跌额(元)" prop="priceAmount" align="center" width="120" sortable>
          <template #default="scope">
            <span :class="getPriceClass(scope.row.priceAmount)">
              {{ scope.row.priceAmount > 0 ? '+' : '' }}{{ scope.row.priceAmount.toFixed(2) }}
            </span>
          </template>
        </el-table-column>

        <el-table-column label="换手率(%)" prop="turnoverRate" align="center" width="100" sortable>
          <template #default="scope">
            <span>{{ scope.row.turnoverRate.toFixed(2) }}%</span>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" align="center" width="180">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" type="primary" class="action-btn" @click="handleDetail(scope.row)">
                <el-icon>
                  <View />
                </el-icon>
                <span>详情</span>
              </el-button>
              <el-button size="small" type="success" class="action-btn" @click="handleAnalysis(scope.row)">
                <el-icon>
                  <DataAnalysis />
                </el-icon>
                <span>分析</span>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination 
          v-model:current-page="currentPage" 
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]" 
          layout="total, sizes, prev, pager, next, jumper" 
          :total="totalStocks"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>

      <div class="empty-placeholder" v-if="filterTableData.length === 0 && !loading">
        <el-empty description="暂无股票数据" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  RefreshRight, 
  View, 
  DataAnalysis, 
  Notebook, 
  Calendar
} from '@element-plus/icons-vue'

// 定义股票数据接口
interface StockData {
  id: number
  date: string         // 交易日
  code: string         // 股票代码
  open: number         // 开盘价
  close: number        // 收盘价
  high: number         // 最高价
  low: number          // 最低价
  volume: number       // 成交量（手）
  amount: number       // 成交额（元）
  amplitude: number    // 振幅（%）
  priceChange: number  // 涨跌幅（%）
  priceAmount: number  // 涨跌额（元）
  turnoverRate: number // 换手率（%）
}

// 表格数据
const stockList = ref<StockData[]>([]);
const loading = ref(false);

// 初始化示例数据
const initStockData = () => {
  loading.value = true;
  
  // 模拟API加载数据
  setTimeout(() => {
    stockList.value = [
      {
        id: 1,
        date: "2025-04-20",
        code: "600036",
        open: 40.15,
        close: 41.28,
        high: 41.56,
        low: 40.01,
        volume: 251436,
        amount: 5632458.65,
        amplitude: 3.86,
        priceChange: 2.82,
        priceAmount: 1.13,
        turnoverRate: 2.35
      },
      {
        id: 2,
        date: "2025-04-20",
        code: "601318",
        open: 68.75,
        close: 67.92,
        high: 69.15,
        low: 67.55,
        volume: 389245,
        amount: 18526478.92,
        amplitude: 2.36,
        priceChange: -1.21,
        priceAmount: -0.83,
        turnoverRate: 1.87
      },
      {
        id: 3,
        date: "2025-04-20",
        code: "000001",
        open: 15.45,
        close: 15.48,
        high: 15.67,
        low: 15.32,
        volume: 562378,
        amount: 8752643.27,
        amplitude: 2.27,
        priceChange: 0.19,
        priceAmount: 0.03,
        turnoverRate: 2.98
      },
      {
        id: 4,
        date: "2025-04-19",
        code: "600036",
        open: 39.87,
        close: 40.15,
        high: 40.45,
        low: 39.75,
        volume: 232156,
        amount: 5123478.35,
        amplitude: 1.76,
        priceChange: 0.73,
        priceAmount: 0.28,
        turnoverRate: 2.12
      },
      {
        id: 5,
        date: "2025-04-19",
        code: "601318",
        open: 69.25,
        close: 68.75,
        high: 69.45,
        low: 68.55,
        volume: 356789,
        amount: 16857496.35,
        amplitude: 1.31,
        priceChange: -0.72,
        priceAmount: -0.50,
        turnoverRate: 1.65
      },
      {
        id: 6,
        date: "2025-04-18",
        code: "000001",
        open: 15.67,
        close: 15.45,
        high: 15.79,
        low: 15.38,
        volume: 498756,
        amount: 7856234.18,
        amplitude: 2.65,
        priceChange: -1.43,
        priceAmount: -0.22,
        turnoverRate: 2.56
      },
      {
        id: 7,
        date: "2025-04-18",
        code: "603777",
        open: 25.35,
        close: 26.12,
        high: 26.38,
        low: 25.18,
        volume: 187645,
        amount: 4856723.45,
        amplitude: 4.74,
        priceChange: 3.04,
        priceAmount: 0.77,
        turnoverRate: 3.12
      }
    ];
    
    totalStocks.value = stockList.value.length;
    loading.value = false;
  }, 800);
};

// 搜索和分页
const search = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const totalStocks = ref(0);

// 日期范围筛选
const dateRange = ref([]);

// 过滤表格数据
const filterTableData = computed(() => {
  let filtered = stockList.value;
  
  // 根据股票代码搜索
  if (search.value) {
    filtered = filtered.filter(
      (data) => data.code.toLowerCase().includes(search.value.toLowerCase())
    );
  }
  
  // 根据日期范围筛选
  if (dateRange.value && dateRange.value.length === 2) {
    const startDate = dateRange.value[0];
    const endDate = dateRange.value[1];
    
    filtered = filtered.filter(
      (data) => data.date >= startDate && data.date <= endDate
    );
  }
  
  return filtered;
});

// 处理涨跌幅颜色显示
const getPriceClass = (value: number) => {
  if (value > 0) return 'price-up';
  if (value < 0) return 'price-down';
  return '';
};

// 格式化成交量数字（千分位）
const formatNumber = (num: number) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

// 格式化成交额（万元或亿元）
const formatCurrency = (num: number) => {
  if (num >= 100000000) {
    return (num / 100000000).toFixed(2) + '亿';
  } else if (num >= 10000) {
    return (num / 10000).toFixed(2) + '万';
  } else {
    return num.toFixed(2);
  }
};

// 刷新数据
const handleRefresh = () => {
  ElMessage.success('数据刷新中...');
  initStockData();
};

// 日期变更
const handleDateChange = (val: any) => {
  console.log('日期范围变更:', val);
};

// 查看详情
const handleDetail = (row: StockData) => {
  ElMessage.success(`查看股票 ${row.code} 的详细数据`);
};

// 分析数据
const handleAnalysis = (row: StockData) => {
  ElMessage.info(`分析股票 ${row.code} 的趋势数据`);
};

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
};

// 初始化数据
onMounted(() => {
  initStockData();
});

</script>

<style scoped>
.stock-list-container {
  padding: 20px;
  margin: 0 auto;
}

.table-container {
  background-color: #f9f9fb;
  border-radius: 10px;
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(216, 218, 219, 0.15);
  padding: 20px;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
}

.table-container::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.8) 0%, rgba(245, 247, 250, 0.6) 100%);
  border-radius: 8px;
  z-index: -1;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 5px 15px;
  margin-bottom: 10px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.create-btn {
  border-radius: 20px;
}

.create-btn:hover {
  transform: scale(1.05);
}

.btn-icon {
  font-size: 16px;
  margin-right: 4px;
}

.date-picker {
  width: 320px;
  border-radius: 20px;
}

.search-input {
  width: 240px;
  border-radius: 20px;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 20px;
  background: #f9f9fb;
  box-shadow: 0 0 0 1px rgba(64, 158, 255, 0.2);
  padding: 8px 16px;
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper:hover) {
  background: #f0f5fb;
  box-shadow: 0 0 0 1px #409EFF;
}

.search-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409EFF, 0 0 0 3px rgba(64, 158, 255, 0.2);
}

.search-input :deep(.el-input__inner) {
  color: #606266;
}

.water-drop-table {
  margin-top: 16px;
  border-radius: 8px;
  overflow: hidden;
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.water-drop-table :deep(.el-table__row) {
  transition: all 0.3s ease;
}

.water-drop-table :deep(.el-table__row:hover) {
  background-color: #f0f7ff !important;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.water-drop-table :deep(td.el-table__cell) {
  padding: 10px;
}

.table-cell-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.cell-icon {
  color: #409EFF;
  font-size: 14px;
  background-color: rgba(236, 245, 255, 0.6);
  padding: 4px;
  border-radius: 4px;
}

.price-up {
  color: #f56c6c;
  font-weight: 500;
}

.price-down {
  color: #67c23a;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-btn {
  border-radius: 16px;
  transition: all 0.3s ease;
  padding: 6px 10px;
}

.action-btn:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.empty-placeholder {
  height: 200px;
  padding: 40px 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-empty {
  padding: 0;
}
</style>